﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using Twitterizer;
using TwiMixer.RESTAPI;
using System.Configuration;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;


namespace TwiMixer
{
    public static class Utility
    {
        private static readonly string basePath = HttpContext.Current.Request.PhysicalApplicationPath;
        private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
        private static string RandomString(int size)
        {
            StringBuilder builder = new StringBuilder();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }

        /*
        public static void SaveUserToken(OAuthTokenResponse response, string apiProviderName)
        {
            
            string xmlFile = basePath + @"\user\";

            //string xmlFile = @"d:\TwiMixerWorkspace\user\";
            xmlFile += apiProviderName + @"\" + response.UserId + ".tm";

            XmlTextWriter writer = new XmlTextWriter(xmlFile, null);

            writer.Formatting = Formatting.Indented;
            writer.Indentation = 3;
            writer.WriteStartDocument();
            writer.WriteStartElement("TwiMixer");

            writer.WriteStartElement("RESTAPI");
            writer.WriteStartElement("API");
            writer.WriteAttributeString("Name", apiProviderName);
            writer.WriteAttributeString("Enabled", "true");
            writer.WriteAttributeString("ScreenName", response.ScreenName);
            writer.WriteAttributeString("UserId", response.UserId.ToString());
            writer.WriteElementString("Token", response.Token);
            writer.WriteElementString("Secret", response.TokenSecret);

            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
        }
         */

        public static string SaveUserToken(OAuthTokenResponse response, string apiProviderName) 
        {
            string fileContent = response.Token +"&"+ response.TokenSecret;
            string filePath = basePath + @"\user\";
            string uId = RandomString(5);
            filePath +=uId+ ".token";

            File.WriteAllText(filePath, fileContent);

            return uId;

            //File.WriteAllText(
        }

        public static void SaveUserToken(string responseToken, string apiProviderName)
        {
            string oauth_token = Regex.Match(responseToken, "oauth_token=([^&]+)").Groups[1].Value;
            string oauth_token_secret = Regex.Match(responseToken, "oauth_token_secret=([^&]+)").Groups[1].Value;

            string tokenFile = basePath + @"\user\";
            tokenFile += apiProviderName + @"\" + oauth_token;

            File.WriteAllText(tokenFile, oauth_token_secret);
        }

        public static void SaveLog(string logText, string apiProviderName) 
        {
            string tokenFile = basePath + @"\logs\";
            tokenFile += apiProviderName + @".log" ;

            File.AppendAllText(tokenFile, logText);
        }

        public static string GetTokenSecret(string oauth_token,string apiProviderName) 
        {
            string tokenFile = basePath + @"\user\";
            tokenFile += apiProviderName + @"\" + oauth_token;

            try
            {
                return File.ReadAllText(tokenFile);
            }
            catch (Exception)
            {
                
                //throw;
            }
            return string.Empty;

        }

        public static OAuthTokens LoadUserToken(string path)
        {
            string[] requestPath = path.Split('/');
            OAuthTokens token = new OAuthTokens();

            if (requestPath.Length != 6)
            {
                ///返回地址无效页面 未完成
                string xmlFile = basePath + @"\user\";
                xmlFile += requestPath[2] + @"\" + requestPath[3] + ".tm";

                XmlTextReader reader = new XmlTextReader(xmlFile);
                reader.ReadStartElement("TwiMixer");
                reader.ReadStartElement("RESTAPI");
                while (reader.Read())
                {
                    ///确定api类型是否相符 sina=s twitter=t
                    ///为以后个人配置保存在单个文件做准备 现在用不到
                    if (reader.GetAttribute("name") == requestPath[2] && reader.NodeType == XmlNodeType.Element)
                    {
                        reader.ReadStartElement("API");
                        token.AccessToken = reader.ReadElementString("token");
                        token.AccessTokenSecret = reader.ReadElementString("secret");
                    }
                }
                reader.Close();
            }
            return token;
        }

        public static void LoadProviderConfig(ref OAuthTokens token, APIProviderEnum api)
        {
            switch (api)
            {
                case APIProviderEnum.twimixer:
                    break;
                case APIProviderEnum.tweet:
                    token.ConsumerKey = ConfigurationManager.AppSettings["Twitter_Consumer_Key"];
                    token.ConsumerSecret = ConfigurationManager.AppSettings["Twitter_Consumer_Secret"];
                    break;
                case APIProviderEnum.sina:
                    token.ConsumerKey = ConfigurationManager.AppSettings["Sina_App_Key"];
                    token.ConsumerSecret = ConfigurationManager.AppSettings["Sina_App_Secret"];
                    break;
                case APIProviderEnum.tencent:
                    break;
                default:
                    break;
            }

        }

        public static OAuthTokenResponse Token2TokenResponse(OAuthTokens token) 
        {
            return new OAuthTokenResponse { Token = token.AccessToken, TokenSecret = token.AccessTokenSecret };
        }

        public static OAuthTokens TokenResponse2Token(OAuthTokenResponse token) 
        {
            return new OAuthTokens { AccessToken = token.Token, AccessTokenSecret = token.TokenSecret };
        }

        //把api代理的path中的用户信息部分去掉 返回api实际路径
        public static string GetProviderPath(string path) 
        {
            return Regex.Match(path, @"(/\w+/\w+\d+)([^?]+)").Groups[2].Value;
        }
    }
}